<template>
	<view class="code-container">
		<!-- 我的二维码 -->
		<view class="code-card">
			<image class="qrcode" :src="qrcodeUrl" mode="aspectFit" @longpress="saveCode"/>
			<text class="code-tip">长按保存二维码</text>
			<!-- <button class="save-btn" @click="saveCode">一键保存</button> -->
		</view>
		<!-- 推广商信息卡片 -->
		<!-- <view v-if="userInfo.parent_user_id" class="info-card">
			<view class="info-content">
				<view class="info-item">
					<text class="label">上级推广人</text>
					<text class="value">{{ parentInfo.nickname || '暂无' }}</text>
				</view>
			</view>
		</view> -->
		
		<!-- 下级用户列表卡片 -->
		<view v-if="childUsers.length > 0" class="child-users-card">
			<view class="card-header">
				<text class="card-title">我的游客 ({{childUsers.length}})</text>
			</view>
			<view class="child-users-list">
				<view 
					class="child-user-item" 
					v-for="(user, index) in childUsers" 
					:key="user.id"
				>
					<image 
						class="user-avatar" 
						:src="user.avatar_url || '/static/default_user.png'" 
						mode="aspectFill"
					/>
					<view class="user-info">
						<text class="user-name">{{user.nickname || '未设置昵称'}}</text>
					</view>
					<text class="join-time"></text>
				</view>
			</view>
		</view>
		
		<!-- 无下级用户提示 -->
		<view v-else class="empty-child-users">
			<u-empty text="暂无游客" mode="data"></u-empty>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			qrcodeUrl: '',
			parentInfo: {},
			distributionRate: '',
			distributionId: null,
			parentDistribution: null,
			minValue: 100, // 最小推广比例
			childUsers: [] // 新增：下级用户列表
		}
	},
	onLoad() {
		uni.showLoading({
			title: '加载中'
		})
		this.$store.dispatch('getUserInfo').then(res => {
			if (res.invite_qr_code) {
				this.qrcodeUrl = res.invite_qr_code
			} else {
				setTimeout(() => {
					uni.showLoading({
						title: '加载中'
					})
				}, 300)
				this.$api.getUserQrCode({ user_id: this.userInfo.id }).then(res => {
					this.qrcodeUrl = res
				}).finally(() => {
					uni.hideLoading()
				})
			}
			// 获取推广设置
			if (res.parent_user_id) {
				// 获取上级用户信息
				this.$api.getUserInfo(res.parent_user_id).then(parentRes => {
					this.parentInfo = parentRes
				})

			}
			// this.getDistributionSettings()
		})
		this.$api.getUserList({
			parent_user_id: this.userInfo.id,
		}).then(res => {
			this.childUsers = res
		})
	},
	methods: {
		saveCode() {
			uni.downloadFile({
				url: this.qrcodeUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({ title: '保存成功', icon: 'success' })
							},
							fail: () => {
								uni.showToast({ title: '保存失败', icon: 'none' })
							}
						})
					}
				},
				fail: () => {
					uni.showToast({ title: '下载失败', icon: 'none' })
				}
			})
		},
		// 获取推广设置
		async getDistributionSettings() {
			try {
				const res = await this.$api.getUserDistributionList({ user_id: this.userInfo.id, user_type: this.userInfo.user_type })
				if (res && res.length > 0) {
					const distribution = res[0]
					this.distributionRate = distribution.rate
					this.distributionId = distribution.id
					if (this.userInfo.user_type === 2) {
						// 设置自己的推广比例
						// this.parentDistribution = this.distributionRate
						this.minValue = res[0].rate || 0
					}
				} else {
					if (this.userInfo.user_type === 2) {
						uni.showModal({
							title: '提示',
							content: '请联系管理员设置推广折扣',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									// 跳转到首页
									uni.navigateBack()
								}
							}
						})
					}
				}


			} catch (error) {
				console.error('获取推广设置失败:', error)
			}
		},
		getUserType(type) {
			//  '1 普通用户 2 商家 3 一级分销商 4 二级分销商'
			switch (type) {
				case 1:
					return '普通用户'
				case 2:
					return '商家'
				case 3:
					return '经纪人'
				case 4:
					return '二级分销商'
				default:
					return '普通用户'
			}
		},
		// 更新推广比例
		async updateDistributionRate() {
			const rate = parseInt(this.distributionRate)
			if (!rate || rate < this.minValue - 1 || rate > 101) {
				uni.showToast({
					title: `请输入${this.minValue}-100的数值`,
					icon: 'none'
				})
				return
			}
			uni.showLoading({
				title: '保存中',
				mask: true,
			})

			try {
				const data = {
					rate: rate,
					user_id: this.userInfo.id,
					user_type: this.userInfo.user_type
				}

				if (this.distributionId) {
					// 更新
					await this.$api.updateUserDistribution(this.distributionId, {
						...data
					})
				} else {
					// 创建
					await this.$api.createUserDistribution(data)
				}

				uni.showToast({
					title: '设置成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('更新推广比例失败:', error)
				uni.showToast({
					title: '设置失败',
					icon: 'none'
				})
			}
		},
		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return ''
			const date = new Date(timestamp)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}`
		}
	}
}
</script>

<style lang="scss">
.code-container {
	min-height: 100vh;
	background: #F5F5F5;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 32rpx;
}

// 卡片通用样式
.info-card,
.code-card,
.distribution-settings {
	width: 100%;
	background: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
	margin-bottom: 32rpx;
	overflow: hidden;
}

.card-header {
	padding: 32rpx;
	border-bottom: 2rpx solid #f5f5f5;
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

// 推广商信息卡片样式
.info-content {
	padding: 32rpx;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;

	&:last-child {
		margin-bottom: 0;
	}
}

.label {
	font-size: 28rpx;
	color: #666;
}

.value {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

// 二维码卡片样式
.code-card {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.qrcode {
	width: 260px;
	height: 260rpx;
	margin: 32rpx 0;
	border-radius: 16rpx;
}

.code-tip {
	color: #888;
	font-size: 26rpx;
	margin-bottom: 32rpx;
}

.save-btn {
	width: 80%;
	height: 80rpx;
	background: #FFD29F;
	color: #fff;
	font-size: 32rpx;
	border-radius: 16rpx;
}

// 推广设置样式
.setting-content {
	padding: 32rpx;
}

.setting-item {
	margin-bottom: 32rpx;
}

.setting-input {
	display: flex;
	align-items: center;
	border: 2rpx solid #eee;
	border-radius: 12rpx;
	padding: 0 24rpx;
	height: 80rpx;
	margin-top: 32rpx;
}

.setting-input input {
	flex: 1;
	height: 100%;
	font-size: 28rpx;
}

.unit {
	font-size: 28rpx;
	color: #666;
	margin-left: 8rpx;
}

.setting-tip {
	font-size: 24rpx;
	color: #999;
	margin-top: 8rpx;
	display: block;
}

.setting-btn {
	width: 100%;
	height: 80rpx;
	background: #FFD29F;
	color: #fff;
	font-size: 32rpx;
	border-radius: 12rpx;
}

// 下级用户列表样式
.child-users-card {
	width: 100%;
	background: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
	margin-bottom: 32rpx;
	overflow: hidden;
}

.child-users-list {
	padding: 32rpx;
}

.child-user-item {
	display: flex;
	align-items: center;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #f5f5f5;

	&:last-child {
		border-bottom: none;
	}
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	margin-right: 24rpx;
}

.user-info {
	flex: 1;
	margin-right: 24rpx;
}

.user-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.user-type {
	font-size: 24rpx;
	color: #888;
}

.join-time {
	font-size: 24rpx;
	color: #888;
}

// 无下级用户提示样式
.empty-child-users {
	padding: 32rpx;
}
</style>
